import React from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import '../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styles from './index.less';

const convertToSate = html => {
  const contentBlock = htmlToDraft(html);
  if (contentBlock) {
    const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
    const editorState = EditorState.createWithContent(contentState);
    return editorState;
  }
};

class DraftEditor extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onEditorStateChange = editorState => {
    const { onChange } = this.props;
    const value = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    onChange(value);
  };

  // uploadCallback = file => {
  //   return new Promise((resolve, reject) => {
  //     const reader = new FileReader();
  //     reader.onloadend = () => {
  //       try {
  //         resolve({});
  //       } catch (e) {
  //         reject(e);
  //       }
  //     };

  //     reader.readAsDataURL(file);
  //   });
  // };

  render() {
    const html = this.props.value || '<br/>';
    const editorState = convertToSate(html);
    // const config = {
    //   image: { uploadCallback: this.uploadCallback, urlEnabled: false },
    // };

    return (
      <Editor
        wrapperClassName={styles['editor-wrapper']}
        editorClassName={styles.editor}
        toolbarClassName={styles['editor-toolbar']}
        editorState={editorState}
        localization={{ locale: 'zh' }}
        // toolbar={config}
        onEditorStateChange={this.onEditorStateChange}
      />
    );
  }
}

export default DraftEditor;
